package com.lovepick.fragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.lovepick.R;
import com.lovepick.adapter.MsgItemAdapter;
import com.lovepick.bean.MsgItem;
import com.lovepick.bean.MsgListItem;
import com.lovepick.database.MsgDbManager;
import com.lovepick.database.MsgListDbManager;
import com.lovepick.http.HttpThread;
import com.lovepick.util.BaseUtils;
import com.lovepick.util.Constant;
import com.lovepick.util.MsgType;

public class MsgFragment extends Fragment
{
	public static final String ARG_USERID = "user_id";
	public static final String ARG_NICKNAME = "nickname";
	public static final String ARG_ROLE = "role";
	public boolean isInfoVisible = false;

	private static final String TAG = "MsgFragment";

	private EditText edtMsgContent;
	private ListView lvMsgList;
	private ImageButton btnSendMsg;

	private List<MsgItem> mMsgItems = null;
	private MsgItemAdapter mAdapter = null;
	private String mNickName = "";
	private int mUserID = 0;

	private MsgHandler mHandler = null;
	private HttpThread mThread = null;
	private MsgDbManager mDbManager = null;
	private MsgListDbManager mListDbManager = null;
	private MsgItem mNewItem = null;

	public static MsgFragment createInstance(int userID, String nickName)
	{
		Log.i(TAG, "---createInstance(int userID, String nickName)---");
		MsgFragment fragment = new MsgFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_USERID, userID);
		args.putString(ARG_NICKNAME, nickName);
		fragment.setArguments(args);
		return fragment;
	}

	public static Fragment createInstance(Bundle data)
	{
		Log.i(TAG, "---createInstance(Bundle data)---");
		Fragment fragment = new MsgFragment();
		fragment.setArguments(data);
		return fragment;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
		Log.i(TAG, "---onActivityCreated---");
		super.onActivityCreated(savedInstanceState);
		setHasOptionsMenu(true);
		findViews();
		getActivity().getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		mDbManager = new MsgDbManager();
		mListDbManager = new MsgListDbManager();

		mHandler = new MsgHandler(this);
		Bundle args = getArguments();
		if (args.containsKey(ARG_USERID))
		{
			mUserID = args.getInt(ARG_USERID);
			mNickName = args.getString(ARG_NICKNAME);
			init();
		}

		btnSendMsg.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				sendMsg();
			}
		});

		getActivity().getActionBar().setTitle("与" + mNickName+ "会话");
	}

	private void init()
	{
		Log.i(TAG, "---init()---");
		isInfoVisible = false;
		mMsgItems = mDbManager.getMsgItems(mUserID);

		if (null == mMsgItems)
		{
			mMsgItems = new ArrayList<MsgItem>();
		}

		mAdapter = new MsgItemAdapter(getActivity(), mMsgItems);
		lvMsgList.setAdapter(mAdapter);
		if (mMsgItems.size() != 0)
		{
			lvMsgList.setSelection(mMsgItems.size() - 1);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		Log.i(TAG, "---onCreateView---");
		return inflater.inflate(R.layout.msg, container, false);
	}

	@Override
	public void onPrepareOptionsMenu(Menu menu)
	{
		if (null == mMsgItems)
		{
			menu.findItem(R.id.menu_msg_delete).setEnabled(false);
		}
		else {
			menu.findItem(R.id.menu_msg_delete).setEnabled(true);
		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
	{
		inflater.inflate(R.menu.msg, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.menu_msg_delete:
				deleteMsgs();
				return true;

			default:
				return super.onOptionsItemSelected(item);
		}
	}

	private void findViews()
	{
		Log.i(TAG, "---findViews---");
		btnSendMsg = (ImageButton) getActivity().findViewById(R.id.btn_send_msg);
		edtMsgContent = (EditText) getActivity().findViewById(R.id.edt_msgcontent);
		lvMsgList = (ListView) getActivity().findViewById(R.id.lv_msglist);
	}

	private void sendMsg()
	{
		String content = edtMsgContent.getText().toString();

		if (Constant.EMPTY_STRING.equals(content))
		{
			BaseUtils.showToast(getActivity(), R.string.msg_send_empty);
		}
		else
		{
			mNewItem = new MsgItem();
			String currentDate = BaseUtils.getCurrentDate();
			mNewItem.setContent(content);
			mNewItem.setDate(currentDate);
			mNewItem.setMsgType(MsgType.SEND);

			String url = Constant.HTTP_URL_SEND_MSG;
			url += mUserID;
			url += "&_r=" + String.valueOf(Math.random());
			List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
			paramsList.add(new BasicNameValuePair("message", content));
			mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_POST, url, paramsList);
			mThread.start();
			BaseUtils.showToast(getActivity(), R.string.msg_sending);
		}
	}

	/**
	 * 有新消息到达时, 如果MsgFrament可见, 会调用此函数刷新界面, 显示新消息.
	 */
	public void updateMsgs()
	{
		Log.i(TAG, "---updateMsgs---");
		int last = mMsgItems.size();
		List<MsgItem> items = mDbManager.getMsgItemsField(mUserID, last);
		if (items != null)
		{
			mAdapter.addAll(items);
			lvMsgList.setSelection(mMsgItems.size() - 1);
		}
	}

	private void deleteMsgs()
	{
		Log.i(TAG, "delete all msgs!");
		mDbManager.deleteMsgAll(mUserID);
		if (mMsgItems != null)
		{
			mMsgItems.clear();
		}
		mAdapter.notifyDataSetChanged();
	}

	private static class MsgHandler extends Handler
	{
		private final String MSGHANDLER_TAG = "MsgHandler";
		private WeakReference<MsgFragment> mReference;
		private MsgFragment mFragment;

		public MsgHandler(MsgFragment fragment)
		{
			mReference = new WeakReference<MsgFragment>(fragment);
		}

		@Override
		public void handleMessage(Message msg)
		{
			mFragment = mReference.get();
			switch (msg.what)
			{
				case Constant.MSG_HTTP_SUCCESS:
					String result = msg.getData().getString(Constant.HTTP_RESULT);
					Log.i(MSGHANDLER_TAG, result);
					if (Constant.HTTP_MSG_SEND_SUCCESS.equals(result))
					{
						BaseUtils.showToast(mFragment.getActivity(), R.string.msg_send_success);
						synchronized (mFragment.mNewItem)
						{
							if (mFragment.mNewItem != null)
							{
								mFragment.edtMsgContent.setText("");

								mFragment.mAdapter.addItem(mFragment.mNewItem);
								mFragment.lvMsgList.setSelection(mFragment.mMsgItems.size() - 1);
								Log.i(MSGHANDLER_TAG, "新发送的消息写入数据库");
								mFragment.mDbManager.addMsg(mFragment.mUserID, mFragment.mNewItem);

								MsgListItem item = new MsgListItem();
								item.setUserID(mFragment.mUserID);
								item.setNickName(mFragment.mNickName);
								item.setLastMsg(mFragment.mNewItem.getContent());
								item.setLastDate(mFragment.mNewItem.getDate());
								item.setHasNew(0);
								if (mFragment.mListDbManager.hasUser(mFragment.mUserID))
								{
									mFragment.mListDbManager.updateMsgListItem(item);
								}
								else
								{
									mFragment.mListDbManager.addMsgListItem(item);
								}

								mFragment.mNewItem = null;

							}
						}
					}
					else
					{
						BaseUtils.showToast(mFragment.getActivity(), R.string.msg_send_fail);
					}
					break;

				default:
					break;
			}
		}
	}

}
